﻿using SqlSugar;
using System.Reflection;

namespace Zy.Shared.Repository.ClickHouse.DbContext
{
    public class SqlSugarDbContext(ZyUserContext user)
    {
        public void SetAuditFields(object sql, DataFilterModel pars)
        {
            SqlSugarAuditFullEntity auditEntity = new();
            switch (pars.OperationType)
            {
                case DataFilterType.InsertByObject:
                    if (typeof(IAuditEntity).IsAssignableFrom(pars.EntityValue.GetType()) && pars.PropertyName == "CreateTime")//TODO:此处的字段名需要更好的办法
                    {
                        var value = pars.EntityValue as IAuditEntity;
                        value.CreateTime = DateTime.Now;
                        value.CreateBy=user.Id;
                        //value.GetType().GetProperties().FirstOrDefault(x => x.Name == "CreateTime")?.SetValue(value, DateTime.Now);
                        //value.GetType().GetProperties().FirstOrDefault(x => x.Name == "CreateBy")?.SetValue(value, user.Id);
                    }
                    break;
                case DataFilterType.UpdateByObject:
                    if (typeof(IAuditFullEntity).IsAssignableFrom(pars.EntityValue.GetType()) && pars.PropertyName == "ModifyTime")
                    {
                        var value = pars.EntityValue as IAuditFullEntity;
                        value.ModifyTime = DateTime.Now;
                        value.ModifyBy = user.Id;
                    }
                    break;
                case DataFilterType.DeleteByObject:
                    break;
            }
        }

        public static void InitTables(List<Type> entities, ISqlSugarClient sqlSugar)
        {
            var tables = sqlSugar.DbMaintenance.GetTableInfoList();
            var adds = entities.Where(x => !tables.Select(s => s.Name).Contains(x.GetCustomAttributes<SugarTable>(true).FirstOrDefault()?.TableName)).ToArray();
            if (adds.Length > 0)
                sqlSugar.CodeFirst.InitTables(adds);
        }
    }
}
